package com.youkeda.service.impl;

import com.youkeda.model.Course;
import com.youkeda.model.CourseTimetable;
import com.youkeda.model.Timetable;
import com.youkeda.model.WeekPlan;
import com.youkeda.service.CourseTimetableService;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author xshuai
 */
public class CourseTimetableServiceImpl implements CourseTimetableService {
    private List<CourseTimetable> courseTimetableList = new ArrayList<>();

    @Override
    public void invoke(CourseTimetable courseTimetable, LocalDateTime startDay, LocalDateTime endDay, List<WeekPlan> weekPlans) {
        if (courseTimetable.getTimetables() == null) {
            courseTimetable.setTimetables(new ArrayList<>());
        }
        Course course = courseTimetable.getCourse();
        long days = Duration.between(startDay, endDay).toDays();
        int sections = course.getSections();
        Timetable timeTable;
        for (int i = 0; i < days; i++) {
            if (sections == 0) {
                break;
            }
            LocalDateTime now = startDay.plusDays(i);
            for (WeekPlan weekPlan :
                    weekPlans) {
                int weekDay = weekPlan.getWeekDay();
                if (now.getDayOfWeek().getValue() == weekDay) {
                    sections = sections - weekPlan.getCount();
                    timeTable = new Timetable();
                    timeTable.setId(UUID.randomUUID().toString());
                    if ("am".equals(weekPlan.getTime())) {
                        timeTable.setStartTime(now.withHour(8));
                    } else {
                        timeTable.setStartTime(now.withHour(13));
                    }
                    timeTable.setEndTime(timeTable.getStartTime().plusHours(weekPlan.getCount()));
                    courseTimetable.getTimetables().add(timeTable);
                }
            }
        }
        courseTimetableList.add(courseTimetable);
    }

    @Override
    public CourseTimetable queryForClasses(String classesId) {
        for (CourseTimetable c :
                courseTimetableList) {
            if (c.getClasses().getId().equals(classesId)) {
                return c;
            }
        }
        return null;
    }
}
